package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class BioChat {
    private static List<Socket> sockets=new ArrayList<>();
    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket=new ServerSocket(9000);
        while (true){
            Socket socket = serverSocket.accept();
            sockets.add(socket);
            socket.getOutputStream().write(("I am Server,your port: "+socket.getPort()+"\n").getBytes());
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            new Thread(){
                @Override
                public void run() {
                    while (true){
                        String info = null;
                        try {
                            info = reader.readLine();
                            if(info.startsWith("bye")){
                                socket.close();
                                sockets.remove(socket);
                                break;
                            }
                            send(socket,info);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println(info);
                    }
                }
            }.start();
        }
    }

    private static void send(Socket socket,String info){
        for (int i = 0; i < sockets.size(); i++) {
            Socket sk = sockets.get(i);
            if(sk!=socket){
                try {
                    sk.getOutputStream().write((info+"\n").getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
